//
//  Utils.m
//  AnhChe
//
//  Created by Nguyen Cong Huy on 7/30/14.
//  Copyright (c) 2014 Nguyen Cong Huy. All rights reserved.
//

#import "Utils.h"
#if ENABLE_GOOGLE_ANALYTIC
#import "GAIDictionaryBuilder.h"
#import "GAIFields.h"
#endif

UIImage* highLightImage;

@implementation Utils

+ (NSString*)convertToUnicodeFromUnicodeEscape:(NSString*)originString {
    NSString* result = [NSString stringWithCString:[originString cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
    return result;
}

+ (int)getIntFromDictionary:(NSDictionary*)dictionary withKey:(NSString*)key {
    NSNumber* number = [dictionary objectForKey:key];
    if(number && [number isKindOfClass:[NSNumber class]]) {
        return [number intValue];
    }
    return 0;
}

+ (void)showErrorConnection {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Thông báo" message:@"Có lỗi kết nối, vui lòng thử lại sau" delegate:nil cancelButtonTitle:@"Đóng" otherButtonTitles:nil];
    [alertView show];
}

+ (UIImage*)cropImage:(UIImage*)srcImage withCropRect:(CGRect)cropRect {
    CGImageRef imageRef = CGImageCreateWithImageInRect([srcImage CGImage], cropRect);
    UIImage* image = [UIImage imageWithCGImage:imageRef scale:srcImage.scale orientation:srcImage.imageOrientation];
    CGImageRelease(imageRef);
    return image;
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage*)getHighLightImage {
    if(highLightImage == nil) {
        highLightImage = [Utils imageWithColor:[UIColor lightGrayColor] size:CGSizeMake(1, 1)];
    }
    return highLightImage;
}

#if ENABLE_GOOGLE_ANALYTIC
+ (void)sendTrackWithCategory:(NSString*)category action:(NSString*)action label:(NSString*)label value:(NSNumber*)value {
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    NSMutableDictionary* trackingEvent = [[GAIDictionaryBuilder createEventWithCategory:category action:action label:label value:value] build];
    [tracker send:trackingEvent];
}

+ (void)sendTrackScreenViewName:(NSString*)screenName {
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker set:kGAIScreenName value:screenName];
    [tracker send:[[GAIDictionaryBuilder createScreenView] build]];
}
#endif

@end
